const http=require('http');
const fs=require('fs');
const path=require('path');

http.createServer((req,res)=>{
    let urlObj=new URL(req.url,'http://localhost:8081');

    let pathName=urlObj.pathname;
    let filePath1=path.join(__dirname,"/index.html");
    let filePath2=path.join(__dirname,"/list.html");
    let filePath3=path.join(__dirname,"/upload");
    if (pathName=='/') {
        fs.readFile(filePath1,(e,data) => {
            if (e) {
                console.log(e);
            }
            else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.end(data);
            }
        })
    }
    else if (pathName=="/list") {
        fs.readFile(filePath2,(e,data) => {
            if (e) {
                console.log(e);
            }
            else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.end(data);
            }
        })
    }
    else if (pathName=="/getlist") {//返回文件夹内图片列表
        let imgArr=[];
        fs.readdir(filePath3,(e,files) => {
            if (e) {
                let sendData=JSON.stringify(imgArr);
                res.writeHead(200,{"Content-Type":"text/json"});
                console.log('sendData:',sendData);
                res.end(sendData); 
            }
            else {
                for (let i=0; i<files.length; i++) {
                    imgArr.push(files[i]);
                }
                let sendData = JSON.stringify(imgArr);
                res.writeHead(200,{"Content-Type":"text/plain"});
                console.log('sendData: ',sendData);
                res.end(sendData); 
            } 
             
        }) 
    }
    else if (pathName=='/upload') {  //对上传图片进行处理
        let str="";
        req.setEncoding("binary");
        req.on('data',chunk=>{
            str+=chunk;
        })
        req.on('end',()=>{
            let dataArr = str.split('\r\n');
            //获得文件名字和文件类型--start
            let fileTypeAndName = dataArr[1].split(';')[2];
            let fileName = fileTypeAndName.slice(11,-1);
            //获得文件名字和文件类型--end
            //获得图片数据并进行类型转换--start
            let myDataArr = dataArr.slice(4,dataArr.length-2);
            let myDataStr = myDataArr.join('\r\n');
            // 将图片转换为二进制数据
            let imgData = Buffer.from(myDataStr,"binary");
            //获得图片数据并进行类型转换--end
            fs.writeFileSync(path.join(filePath3,"/"+fileName),imgData,{"encoding":"binary"});
            res.writeHead(200,{"Content-Type":"text/plain"});
            res.end("success");
        })  
    }
    //这里需要对图片的请求进行处理
    else{
        let firstPN = pathName.split('/');
        if (firstPN[1] == 'upload'&&firstPN[2] != undefined) {//对图片请求中可以返回的部分进行分流
            let childPath = path.join(filePath3,'/'+firstPN[2]);
            fs.readFile(childPath,(err,imgData) => {
                if (err) {
                    console.log(err);
                }
                else{
                    //此处应该返回图片数据
                    res.write(imgData);
                    res.end();
                }
            })
        }
        else{//图片请求中无法处理的部分的分流
            console.log("有其他请求:"+pathName);
            res.end();
        }      
    }
}).listen(8081);
console.log('server is listening 8081');